<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
    append-to-body
  >
    <div v-loading="loading">
      <!-- 学生详细信息 -->
      <el-card shadow="never" class="detail-card">
        <div slot="header" class="clearfix">
          <span class="card-title">👤 学生信息</span>
        </div>
        <el-descriptions :column="2" border v-if="detail.studentName">
          <el-descriptions-item label="学生姓名">
            <span class="student-name">{{ detail.studentName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="学号">
            {{ detail.studentNo }}
          </el-descriptions-item>
          <el-descriptions-item label="年级">
            {{ detail.grade || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="专业">
            {{ detail.major }}
          </el-descriptions-item>
          <el-descriptions-item label="班级">
            {{ detail.className }}
          </el-descriptions-item>
          <el-descriptions-item label="绩点">
            <el-tag :type="getGpaType(detail.gpa)" size="small">
              {{ detail.gpa || '-' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系邮箱" :span="2">
            <span v-if="detail.email" class="email-text">
              <i class="el-icon-message"></i>
              {{ detail.email }}
            </span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="技术栈" :span="2" v-if="detail.techStack">
            <el-tag
              v-for="(tech, index) in parseTechStack(detail.techStack)"
              :key="index"
              size="small"
              type="info"
              style="margin-right: 5px; margin-bottom: 5px;"
            >{{ tech }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="个人简介" :span="2" v-if="detail.personalIntro">
            <div class="intro-text">{{ detail.personalIntro }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 变更信息 -->
      <el-alert
        :type="getAlertType()"
        :closable="false"
        style="margin-bottom: 20px;"
      >
        <template slot="title">
          <div style="font-size: 14px; line-height: 1.8;">
            <strong v-if="isSameTeacher">🔄 学生想在您的题目之间切换</strong>
            <strong v-else-if="isOldTeacher">🔄 该学生想从您的题目换到其他题目</strong>
            <strong v-else>🎯 该学生想换到您的题目</strong>
          </div>
        </template>
        <div style="font-size: 13px; line-height: 1.6; color: #606266; margin-top: 10px;">
          <div><strong>原题目：</strong>{{ detail.oldTopicTitle }}</div>
          <div><strong>新题目：</strong>{{ detail.newTopicTitle }}</div>
          <div v-if="isSameTeacher" style="margin-top: 8px; color: #909399;">
            💡 <strong>提示：</strong>这是在您名下的两个题目之间切换，您同意后即可完成变更
          </div>
        </div>
      </el-alert>

      <!-- 变更理由 -->
      <el-card shadow="never" class="reason-card">
        <div slot="header">
          <strong>📝 变更理由</strong>
        </div>
        <div class="reason-content">
          {{ detail.changeReason }}
        </div>
      </el-card>

      <!-- 审核表单 -->
      <el-card shadow="never" class="review-card">
        <div slot="header">
          <strong>✍️ 您的审核</strong>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="审核意见" prop="opinion">
            <el-radio-group v-model="form.opinion">
              <el-radio label="同意">
                <span style="color: #67C23A;">
                  <i class="el-icon-check"></i> 同意
                </span>
              </el-radio>
              <el-radio label="拒绝">
                <span style="color: #F56C6C;">
                  <i class="el-icon-close"></i> 拒绝
                </span>
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="意见说明" prop="reason">
            <el-input
              type="textarea"
              v-model="form.reason"
              placeholder="请填写审核意见（可选）"
              :rows="4"
              maxlength="200"
              show-word-limit
            />
            <div style="color: #909399; font-size: 12px; margin-top: 5px;">
              {{ form.opinion === '同意' ? '✨ 同意时可不填写意见' : '⚠️ 拒绝时建议填写理由，便于学生了解情况' }}
            </div>
          </el-form-item>
        </el-form>

        <!-- 温馨提示 - 同一教师 -->
        <el-alert
          v-if="form.opinion === '同意' && isSameTeacher"
          type="success"
          :closable="false"
          style="margin-top: 15px;"
        >
          <div style="font-size: 13px; line-height: 1.6;">
            <strong>✅ 同意后（即刻完成）</strong><br/>
            • 学生将从原题目转到新题目<br/>
            • 您的指导学生总数不变<br/>
            • 原题目名额释放一个，新题目名额占用一个
          </div>
        </el-alert>

        <!-- 温馨提示 - 原教师（不同教师） -->
        <el-alert
          v-if="form.opinion === '同意' && !isSameTeacher && isOldTeacher"
          type="success"
          :closable="false"
          style="margin-top: 15px;"
        >
          <div style="font-size: 13px; line-height: 1.6;">
            <strong>✅ 同意后（还需新教师同意）</strong><br/>
            • 该学生将从您的指导名单中移除<br/>
            • 您的指导学生数将 -1<br/>
            • 该题目名额将释放一个
          </div>
        </el-alert>

        <!-- 温馨提示 - 新教师（不同教师） -->
        <el-alert
          v-if="form.opinion === '同意' && !isSameTeacher && !isOldTeacher"
          type="success"
          :closable="false"
          style="margin-top: 15px;"
        >
          <div style="font-size: 13px; line-height: 1.6;">
            <strong>✅ 同意后（原教师已同意）</strong><br/>
            • 该学生将加入您的指导名单<br/>
            • 您的指导学生数将 +1<br/>
            • 该题目名额将占用一个
          </div>
        </el-alert>

        <el-alert
          v-if="form.opinion === '拒绝'"
          type="error"
          :closable="false"
          style="margin-top: 15px;"
        >
          <div style="font-size: 13px;">
            <strong>❌ 拒绝后</strong><br/>
            换题申请将直接结束，学生将保持原状态
          </div>
        </el-alert>
      </el-card>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button
        type="primary"
        @click="submitReview"
        :loading="submitLoading"
        :disabled="!form.opinion"
      >
        确认提交
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getTeacherChangeRequestDetail, reviewAsOldTeacher, reviewAsNewTeacher } from "@/api/system/topicChangeRequest";

export default {
  name: "ReviewDialog",
  data() {
    return {
      dialogVisible: false,
      loading: false,
      submitLoading: false,
      // 详情
      detail: {},
      // 是否是原教师
      isOldTeacher: false,
      // 是否是同一个教师
      isSameTeacher: false,
      // 表单
      form: {
        opinion: '',
        reason: ''
      },
      // 校验规则
      rules: {
        opinion: [
          { required: true, message: "请选择审核意见", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    dialogTitle() {
      if (this.isSameTeacher) {
        return '审核换题申请（同教师内换题）';
      }
      return this.isOldTeacher ? '审核换题申请（原教师）' : '审核换题申请（新教师）';
    }
  },
  methods: {
    /** 打开对话框 */
    open(row, isOldTeacher, isSameTeacher) {
      this.dialogVisible = true;
      this.isOldTeacher = isOldTeacher;
      this.isSameTeacher = isSameTeacher;
      this.getDetail(row.requestId);
    },
    /** 获取详情 */
    getDetail(requestId) {
      this.loading = true;
      getTeacherChangeRequestDetail(requestId).then(response => {
        this.detail = response.data;
        this.loading = false;
      });
    },
    /** 解析技术栈 */
    parseTechStack(techStack) {
      if (!techStack) return [];
      try {
        return JSON.parse(techStack);
      } catch (e) {
        return [];
      }
    },
    /** 绩点标签类型 */
    getGpaType(gpa) {
      if (!gpa) return 'info';
      if (gpa >= 3.5) return 'success';
      if (gpa >= 3.0) return '';
      if (gpa >= 2.5) return 'warning';
      return 'danger';
    },
    /** 获取提示框类型 */
    getAlertType() {
      if (this.isSameTeacher) {
        return 'info';
      }
      return this.isOldTeacher ? 'warning' : 'success';
    },
    /** 提交审核 */
    submitReview() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const confirmMsg = this.form.opinion === '同意'
            ? (this.isSameTeacher 
                ? `确认同意该学生在您的题目间切换？同意后将立即完成变更。`
                : `确认同意该学生的换题申请？`)
            : `确认拒绝该学生的换题申请？`;
          
          this.$confirm(confirmMsg, '确认审核', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.submitLoading = true;
            
            const data = {
              [this.isOldTeacher ? 'oldTeacherOpinion' : 'newTeacherOpinion']: this.form.opinion,
              [this.isOldTeacher ? 'oldTeacherReason' : 'newTeacherReason']: this.form.reason
            };
            
            const apiCall = this.isOldTeacher
              ? reviewAsOldTeacher(this.detail.requestId, data)
              : reviewAsNewTeacher(this.detail.requestId, data);
            
            apiCall.then(() => {
              this.$modal.msgSuccess("审核成功");
              this.dialogVisible = false;
              this.$emit('success');
            }).finally(() => {
              this.submitLoading = false;
            });
          }).catch(() => {});
        }
      });
    },
    /** 关闭对话框 */
    handleClose() {
      this.resetForm();
    },
    /** 重置表单 */
    resetForm() {
      this.form = {
        opinion: '',
        reason: ''
      };
      this.detail = {};
      this.isSameTeacher = false;
      this.isOldTeacher = false;
      this.$refs.form && this.$refs.form.resetFields();
    }
  }
};
</script>

<style scoped lang="scss">
.detail-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.student-name {
  font-size: 15px;
  font-weight: bold;
  color: #409EFF;
}

.email-text {
  color: #409EFF;
  
  i {
    margin-right: 5px;
  }
}

.intro-text {
  color: #606266;
  font-size: 14px;
  line-height: 1.8;
  white-space: pre-wrap;
  word-break: break-word;
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
}

.reason-card {
  margin-bottom: 20px;
  background-color: #f5f7fa;
}

.reason-content {
  line-height: 1.8;
  white-space: pre-wrap;
  word-break: break-word;
  color: #606266;
  font-size: 14px;
}

.review-card {
  margin-bottom: 20px;
}

::v-deep .el-descriptions__label {
  font-weight: bold;
  width: 120px;
}

::v-deep .el-radio {
  margin-right: 30px;
  
  .el-radio__label {
    font-size: 14px;
  }
}
</style>